#ifndef TEMPLE_UTIL_SOCKET_H_
#define TEMPLE_UTIL_SOCKET_H_

#include "util/stdc.h"
namespace util {

int socket_udp_init(int family, const char *addr, int port)
{
	fd = ::socket(family, SOCK_DGRAM, 0);
	if (fd < 0)
		return -1;

	int opt=1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt));

	sockaddr_t sa;

	if (family == AF_INET)
	{
		struct in_addr in;
		int ret;

		ret = ::inet_pton(AF_INET, addr, (void *)&in);
		assert(ret == 1);

		struct sockaddr_in *sa_in = (struct sockaddr_in *)&sa;
		sa_in->sin_family = AF_INET;
		sa_in->sin_port = htons(port);
		sa_in->sin_addr = in;
	}
	else
	{
		assert(family == AF_INET6);

		struct in6_addr in;
		int ret;

		ret = ::inet_pton(AF_INET6, addr, (void *)&in);
		assert(ret == 1);

		struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)&sa;
		sa_in->sin6_family = AF_INET6;
		sa_in->sin6_port = htons(port);
		sa_in->sin6_addr = in;
	}

	if (::bind(fd, &sa, sizeof(sa)) != 0)
		return -1;

	return fd;
}

#endif //TEMPLE_UTIL_SOCKET_H_
